package com.wshl.aijiuunion.controller.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.baidu.mapapi.NetworkUtil;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.HomeActivity;
import com.wshl.aijiuunion.NetUrl;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.model.RequestModel;
import com.wshl.aijiuunion.utils.BarUtils;
import com.wshl.aijiuunion.utils.share.LoginOutUtils;
import com.wshl.aijiuunion.view.bean.BindPhoneBean;
import com.wshl.aijiuunion.view.bean.EventBeans;
import com.wshl.aijiuunion.view.bean.LoginBean;
import com.wshl.aijiuunion.view.widget.Loadingdialog;
import com.wshl.aijiuunion.view.widget.NofastClickTextview;
import com.wshl.aijiuunion.wxapi.Constancts;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created buy 风凊扬 on 2019/10/21 0021
 */
public class LoginActivity extends AppCompatActivity implements RequestModel.onSendcodeListener {


    @BindView(R.id.et_login_mobile)
    EditText etLoginMobile;
    @BindView(R.id.et_login_code)
    EditText etLoginCode;
    @BindView(R.id.tv_sendcode)
    NofastClickTextview tvSendcode;
    @BindView(R.id.tv_login)
    NofastClickTextview tvLogin;
    @BindView(R.id.img_wxlogin)
    ImageView imgWxlogin;
    @BindView(R.id.tv_xieyi)
    NofastClickTextview tvXieyi;
    @BindView(R.id.rl_wxlogin)
    RelativeLayout rlWxlogin;
    @BindView(R.id.img_xuanze)
    ImageView imgXuanze;
    @BindView(R.id.et_tuijian)
    EditText etTuijian;

    private RequestModel model;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        BarUtils.setStatusBarForActivity(this);
        EventBus.getDefault().register(this);
        model = new RequestModel();
        model.setOnsendCodeListener(this);
        String mobile = SPUtils.getInstance().getString(GlobConstant.MOBILE);
        if (!TextUtils.isEmpty(mobile)) {
            etLoginMobile.setText(mobile);
            etLoginMobile.setSelection(mobile.length());
            imgXuanze.setSelected(true);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @OnClick({R.id.img_xuanze, R.id.tv_xieyi, R.id.tv_sendcode, R.id.tv_login, R.id.img_wxlogin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_xuanze:
                imgXuanze.setSelected(!imgXuanze.isSelected());
                break;
            case R.id.tv_xieyi:
                Intent intent=new Intent(LoginActivity.this,WebActivity.class);
                intent.putExtra(GlobConstant.WEBURL, NetUrl.AGREE);
                ActivityUtils.startActivity(intent);
                break;
            case R.id.tv_sendcode:
                String mobile = etLoginMobile.getText().toString().trim();
                if (TextUtils.isEmpty(mobile)) {
                    ToastUtils.showShort("请输入手机号");
                    return;
                }
                KeyboardUtils.hideSoftInput(LoginActivity.this);
                sendVerifycode(mobile);
                break;
            case R.id.tv_login:
                String phone = etLoginMobile.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtils.showShort("请输入手机号");
                    return;
                }

                String code = etLoginCode.getText().toString().trim();
                if (TextUtils.isEmpty(code)) {
                    ToastUtils.showShort("请输入验证码");
                    return;
                }


                if (!imgXuanze.isSelected()) {

                    ToastUtils.showLong("请勾选用户协议");
                    return;
                }

                String tuijianma = etTuijian.getText().toString().trim();

                login(phone, code, tuijianma);
                break;
            case R.id.img_wxlogin:
                if (!imgXuanze.isSelected()) {

                    ToastUtils.showLong("请勾选用户协议");
                    return;
                }
                wechatLogin();
                break;
        }
    }


    /**
     * 微信登录,第一步,发送请求
     */
    private void wechatLogin() {

        IWXAPI WXapi = WXAPIFactory.createWXAPI(this, Constancts.WXAPPID, true);
        WXapi.registerApp(Constancts.WXAPPID);
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo";
        WXapi.sendReq(req);
    }

    /**
     * 微信登录第二步 在wxEntryActivity中收到用户同意授权后,获取code
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getWxcode(EventBeans eventInfo) {

        String code = eventInfo.getCode();
        String info = eventInfo.getMsg();
        if (code.equals(GlobConstant.WXLOGINGETACCESSTOKEN)) {

            LogUtils.i("微信授权回调code:" + info);
            //根据code 获取access_token
            getAccessToken(info);
        }

        if (code.equals("wxLoginSuccess")) {
            //微信登录成功
            LoginActivity.this.finish();
        }


    }

    /**
     * 微信登陆第三步
     * 获取access_token：
     *
     * @param code 用户或取access_token的code，仅在ErrCode为0时有效
     */
    public void getAccessToken(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" + Constancts.WXAPPID + "&secret=" + Constancts.WXAPPSECRET +
                "&code=" + code + "&grant_type=authorization_code";
        OkGo.<String>get(url)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.i("微信授权登录:" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            String access_token = jsonObject.getString("access_token");
                            String openid = jsonObject.getString("openid");

                            //微信登录第四步
                            getWxinfo(access_token, openid, NetUrl.WXLOGIN);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    /**
     * 微信登录第四步
     *
     * @param openid
     */
    private void getWxinfo(final String acctoken, final String openid, final String url) {

        if (!NetworkUtils.isConnected()) {
            ToastUtils.showLong(getString(R.string.neterror));
            return;
        }
        Loadingdialog.showAlert(this);
        OkGo.<String>post(url)
                .params("openid", openid)
                .params("access_token", acctoken)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(final Response<String> response) {
                        Loadingdialog.dismiss();
                        LogUtils.i("授权登录:" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {

                                String code = jsonObject.getString("code");
                                switch (code) {
                                    case GlobConstant.REQUESTSUCCESS:
                                        BindPhoneBean bindPhoneBean = GsonUtils.fromJson(response.body(), BindPhoneBean.class);

                                        BindPhoneBean.DataBean data = bindPhoneBean.getData();
                                        String token = data.getRemember_token();
                                        String phone = data.getPhone();
                                        SPUtils.getInstance().put(GlobConstant.TOKEN, token);
                                        SPUtils.getInstance().put(GlobConstant.MOBILE, phone);
                                        final boolean isStartMain = SPUtils.getInstance().getBoolean(GlobConstant.ISSTARTMIAN, true);
                                        if (isStartMain) {
                                            ActivityUtils.startActivity(HomeActivity.class);
                                        }

                                        LoginActivity.this.finish();
                                        break;
                                    case "202":
                                        ToastUtils.showLong("请绑定手机号");
                                        Intent intent = new Intent(LoginActivity.this, BindPhoneActivity.class);
                                        intent.putExtra("access_token", acctoken);
                                        intent.putExtra("openid", openid);
                                        ActivityUtils.startActivity(intent);
                                        break;
                                    default:

                                        if (jsonObject.has("msg")) {
                                            ToastUtils.showLong(jsonObject.getString("msg"));
                                        }
                                        break;
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Loadingdialog.dismiss();
                        LogUtils.i("微信授权登录错误:" + response.code() + response.body());
                    }
                });

    }


    private void login(String phone, String code, String tuijianma) {

        if (!NetworkUtils.isConnected()) {
            ToastUtils.showShort(getString(R.string.neterror));
            return;
        }
        Loadingdialog.showAlert(this);
        OkGo.<String>post(NetUrl.LOGIN)
                .tag(this)
                .params("phone", phone)
                .params("code", code)
                .params("referee_code", tuijianma)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        LogUtils.i("登录:" + response.body());
                        Loadingdialog.dismiss();
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {

                                String code = jsonObject.getString("code");

                                if (jsonObject.has("msg")) {
                                    ToastUtils.showShort(jsonObject.getString("msg"));
                                }
                                switch (code) {

                                    case GlobConstant.REQUESTERROR:

                                        break;
                                    case GlobConstant.REQUESTSUCCESS:
                                        LoginBean loginBean = GsonUtils.fromJson(response.body(), LoginBean.class);
                                        LoginBean.DataBean data = loginBean.getData();
                                        String nickname = data.getName();
                                        String avatar = data.getAvatar();
                                        int userid = data.getId();
                                        String mobile = data.getPhone();
                                        String token = data.getRemember_token();
                                        int type = data.getType();
                                        String money = data.getMoney();//余额
                                        String recommend_code = data.getRecommend_code();
                                        SPUtils instance = SPUtils.getInstance();
                                        instance.put(GlobConstant.TOKEN, token);
                                        instance.put(GlobConstant.USERID, userid + "");
                                        instance.put(GlobConstant.MOBILE, mobile);
                                        instance.put(GlobConstant.TYPE, type + "");
                                        instance.put(GlobConstant.NIAKNAME, nickname);
                                        instance.put(GlobConstant.AVATAR, avatar);
                                        instance.put(GlobConstant.MONEY, money);
                                        instance.put(GlobConstant.RECOMMENDCODE, recommend_code);
                                        final boolean isStartMain = SPUtils.getInstance().getBoolean(GlobConstant.ISSTARTMIAN, true);
                                        if (isStartMain) {
                                            ActivityUtils.startActivity(HomeActivity.class);
                                        }

                                        LoginActivity.this.finish();
                                        break;
                                    default:
                                        LogUtils.i("code:" + code);
                                        if (jsonObject.has("msg")) {
                                            ToastUtils.showShort(jsonObject.getString("msg"));
                                        }
                                        break;
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Loadingdialog.dismiss();
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Loadingdialog.dismiss();
                        ToastUtils.showShort("登陆失败,错误码:" + response.code());
                    }
                });
    }


    /**
     * 发送验证码
     */
    private void sendVerifycode(final String mobile) {

        model.sendCode(this, mobile);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);

        model = new RequestModel();
        model.setOnsendCodeListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Loadingdialog.dismiss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelAll();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void start(int s) {
        tvSendcode.setClickable(false);
        tvSendcode.setText(s + "s");
    }

    @Override
    public void end() {
        tvSendcode.setClickable(true);
        tvSendcode.setText("重新发送");
    }


}
